<template>
  <div class="admin-dashboard-container">
    <div class="header-section">
      <div class="header-bg-shape"></div>

      <div class="header-content-wrapper">
        <div class="header-text-area">
          <h1 class="header-title">
            <el-icon class="title-icon">
              <Setting />
            </el-icon>
            管理员控制台
          </h1>
          <p class="header-subtitle">
            <el-icon :size="14" class="quote-icon">
              <List />
            </el-icon>
            管理教师信息，维护平台秩序
          </p>
        </div>

        <div class="header-actions">
          <el-input v-model="searchName" placeholder="搜索教师姓名" @input="fetchTeachers" clearable class="search-input">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="openDialog()" class="add-button">
            <el-icon>
              <Plus />
            </el-icon>
            添加教师
          </el-button>
        </div>
      </div>
    </div>

    <el-card class="data-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <Avatar />
          </el-icon>
          <span>教师列表</span>
        </div>
      </template>
      <el-table :data="filteredTeachers" style="width: 100%" class="teacher-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="department" label="所属部门" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 12px; justify-content: center;">
              <el-button size="small" class="el-button--success" @click="openDialog(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button size="small" class="el-button--danger" @click="handleDelete(scope.row.id)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog append-to-body :title="form.id ? '编辑教师' : '添加教师'" v-model="dialogVisible" width="600px" class="teacher-dialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="form.department" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/authStore';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getAllTeachers,
  createTeacher,
  updateTeacher,
  deleteTeacher,
} from '@/services/teacherService';
import {
  Setting,
  List,
  Search,
  Plus,
  Avatar,
  Edit,
  Delete,
  SwitchButton,
} from '@element-plus/icons-vue';

const teachers = ref([]);
const searchName = ref('');
const dialogVisible = ref(false);
const form = ref({
  id: null,
  username: '',
  name: '',
  email: '',
  phone: '',
  department: '',
  password: '',
});
const formRef = ref();

const router = useRouter();
const authStore = useAuthStore();

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  department: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const fetchTeachers = async () => {
  try {
    const res = await getAllTeachers();
    teachers.value = res.data;
  } catch (error) {
    ElMessage.error('获取教师数据失败');
  }
};

const filteredTeachers = computed(() =>
  teachers.value.filter((t) =>
    t.name.toLowerCase().includes(searchName.value.toLowerCase())
  )
);

const openDialog = (teacher = null) => {
  if (teacher) {
    form.value = { ...teacher, password: '' };
  } else {
    form.value = {
      id: null,
      username: '',
      name: '',
      email: '',
      phone: '',
      department: '',
      password: '',
    };
  }
  dialogVisible.value = true;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      if (form.value.id) {
        await updateTeacher(form.value);
        ElMessage.success('教师信息已更新');
      } else {
        await createTeacher(form.value);
        ElMessage.success('教师添加成功');
      }
      dialogVisible.value = false;
      fetchTeachers();
    } catch (error) {
      ElMessage.error('操作失败，请稍后再试');
    }
  });
};

const handleDelete = async (id) => {
  ElMessageBox.confirm('确定要删除该教师吗？此操作不可逆！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await deleteTeacher(id);
        ElMessage.success('删除成功');
        fetchTeachers();
      } catch (error) {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

const handleLogout = () => {
  authStore.logout();
  router.push({ name: 'Login' });
};

onMounted(fetchTeachers);
</script>

<style scoped>
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.admin-dashboard-container {
  padding: 40px 0 40px 0;
  background: linear-gradient(135deg, #e0e7ef 60%, #f8fafc 100%);
  min-height: calc(100vh - var(--header-height, 60px));
}

/* Header Section - 模拟 Dashboard.vue 的 Hero Section 风格 */
.header-section {
  position: relative;
  display: flex;
  /* 调整：内容靠左，退出按钮靠右 */
  justify-content: space-between;
  /* 修改点：主轴空间均匀分布 */
  align-items: flex-start;
  /* 修改点：顶部对齐，方便将按钮放在右上角 */
  padding: 56px 56px 44px 56px;
  margin-bottom: 36px;
  border-radius: 36px;
  overflow: hidden;
  color: #fff;
  background: rgba(40, 80, 220, 0.55);
  box-shadow: 0 16px 48px -12px rgba(30, 58, 138, 0.18);
  min-height: 240px;
  animation: fadeInUp 0.6s cubic-bezier(.4,2,.6,1) backwards;
  backdrop-filter: blur(18px) saturate(1.2);
  border: 1.5px solid rgba(255,255,255,0.18);
}

.header-bg-shape {
  position: absolute;
  top: -60px;
  right: -100px;
  width: 380px;
  height: 380px;
  background: linear-gradient(135deg, rgba(255,255,255,0.18), rgba(255,255,255,0));
  border-radius: 50%;
  filter: blur(24px);
  z-index: 1;
}

.header-content-wrapper {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 32px;
  flex: 1;
  /* 修改点：让内容区域占据可用空间 */
  align-items: flex-start;
}

.header-text-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.header-title {
  font-size: 2.8rem;
  font-weight: 900;
  margin: 0;
  color: #fff;
  text-shadow: 0 8px 24px rgba(0,0,0,0.13);
  display: flex;
  align-items: center;
  letter-spacing: 1.5px;
}

.title-icon {
  margin-right: 22px;
  font-size: 2.8rem;
  color: #fff;
  filter: drop-shadow(0 2px 8px #2563eb88);
}

.header-subtitle {
  font-size: 1.18rem;
  color: #e0f2fe;
  opacity: 0.95;
  margin: 0;
  max-width: 700px;
  display: flex;
  align-items: flex-start;
  font-weight: 400;
  letter-spacing: 0.5px;
}

.quote-icon {
  flex-shrink: 0;
  margin-right: 14px;
  margin-top: 2px;
  color: #bae6fd;
}

.header-actions {
  display: flex;
  gap: 22px;
  margin-top: 16px;
  align-items: center;
}

.search-input {
  max-width: 240px;
  border-radius: 24px;
  background: rgba(255,255,255,0.22);
  box-shadow: 0 2px 12px rgba(30,58,138,0.08);
  border: 1.5px solid rgba(255,255,255,0.18);
  backdrop-filter: blur(6px);
}

.add-button {
  border-radius: 24px;
  background: linear-gradient(90deg,#22d3ee,#2563eb);
  border: none;
  color: #fff;
  font-weight: 700;
  font-size: 1.08rem;
  padding: 10px 28px;
  box-shadow: 0 2px 8px #2563eb22;
  transition: all 0.18s;
}

.add-button:hover {
  filter: brightness(1.10) saturate(1.2);
  transform: translateY(-2px) scale(1.06);
  box-shadow: 0 6px 18px #2563eb33;
}

/* Data Card - Mimics Grid Card */
.data-card {
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(30,58,138,0.10);
  animation: fadeInUp 0.7s cubic-bezier(.4,2,.6,1) backwards;
  background: rgba(255,255,255,0.82);
  backdrop-filter: blur(8px);
  border: 1.5px solid rgba(40,80,220,0.08);
}

.data-card :deep(.el-card__header) {
  padding: 18px 24px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.data-card .card-header {
  font-weight: 800;
  display: flex;
  align-items: center;
  font-size: 1.22rem;
  color: var(--el-text-color-primary);
  letter-spacing: 1.2px;
}

.data-card .card-header .el-icon {
  margin-right: 12px;
  color: #2563eb;
  filter: drop-shadow(0 2px 8px #2563eb33);
}

/* Table Styling */
.teacher-table {
  border-radius: 14px;
  overflow: hidden;
  font-size: 1.08rem;
  background: transparent;
}

.teacher-table :deep(.el-table__header-wrapper th) {
  background-color: rgba(241,245,249,0.85);
  color: #64748b;
  font-weight: 800;
  font-size: 1.08rem;
  letter-spacing: 0.5px;
}

.teacher-table :deep(.el-table__row) {
  transition: background-color 0.22s cubic-bezier(.4,2,.6,1);
  height: 60px;
  font-size: 1.08rem;
  font-weight: 500;
  letter-spacing: 0.2px;
}

.teacher-table :deep(.el-table__row:hover) {
  background-color: rgba(96,165,250,0.10);
}

.teacher-table :deep(.el-button) {
  border-radius: 22px;
  font-weight: 600;
  padding: 8px 22px;
  transition: all 0.18s;
  font-size: 1.02rem;
  letter-spacing: 0.5px;
}

.teacher-table :deep(.el-button--success),
.teacher-table :deep(.el-button--danger) {
  border-radius: 999px !important;
  font-weight: 600;
  padding: 8px 28px;
  transition: all 0.18s;
  font-size: 1.02rem;
  letter-spacing: 0.5px;
  min-width: 80px;
}

.teacher-table :deep(.el-button--success) {
  background: linear-gradient(90deg,#22d3ee,#2563eb);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px #2563eb22;
}

.teacher-table :deep(.el-button--danger) {
  background: linear-gradient(90deg,#f43f5e,#f59e42);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px #f43f5e22;
}

.teacher-table :deep(.el-button:hover) {
  filter: brightness(1.10) saturate(1.2);
  transform: translateY(-2px) scale(1.06);
  box-shadow: 0 6px 18px #2563eb33;
}

.teacher-table :deep(.el-tag) {
  border-radius: 12px;
  font-size: 1.02rem;
  padding: 4px 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
  box-shadow: 0 2px 8px #2563eb11;
}

/* Dialog Styling */
.teacher-dialog {
  border-radius: 22px !important;
  box-shadow: 0 12px 48px rgba(30,58,138,0.13);
  background: rgba(255,255,255,0.92);
  backdrop-filter: blur(12px);
  border: 1.5px solid rgba(40,80,220,0.10);
}

.teacher-dialog .el-dialog__header {
  border-top-left-radius: 22px;
  border-top-right-radius: 22px;
  background: rgba(241,245,249,0.85);
  color: #2563eb;
  font-weight: 800;
  font-size: 1.18rem;
}

.teacher-dialog .el-dialog__title {
  color: var(--el-color-primary);
  font-weight: 700;
  font-size: 1.2rem;
}

.teacher-dialog .el-form-item {
  margin-bottom: 24px;
}

.teacher-dialog .dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 14px;
}

.el-descriptions {
  background: rgba(248,250,252,0.92);
  border-radius: 16px;
  padding: 12px 0;
  font-size: 1.08rem;
}

.el-descriptions__label {
  color: #2563eb;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.el-descriptions__content {
  color: #334155;
  font-weight: 500;
}
</style>